"""智能性能监控模块

提供实时性能监控、智能分析、预测性维护和自动优化建议。
监控系统性能，收集指标，提供性能优化建议。
"""

import time
import psutil
import threading
import logging
import json
from typing import Dict, List, Any, Optional, Callable
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from collections import defaultdict, deque
from enum import Enum


class AlertLevel(Enum):
    """告警级别"""
    INFO = "info"
    WARNING = "warning"
    CRITICAL = "critical"
    EMERGENCY = "emergency"


class MetricCategory(Enum):
    """指标类别"""
    SYSTEM = "system"
    APPLICATION = "application"
    ALGORITHM = "algorithm"
    NETWORK = "network"
    DATABASE = "database"
    CUSTOM = "custom"


@dataclass
class PerformanceMetric:
    """增强性能指标数据类"""
    name: str
    value: float
    timestamp: datetime
    category: str = "general"
    unit: str = ""
    metadata: Dict[str, Any] = field(default_factory=dict)
    tags: Dict[str, str] = field(default_factory=dict)
    threshold_config: Optional[Dict[str, float]] = None


@dataclass
class PerformanceAlert:
    """性能告警"""
    metric_name: str
    level: AlertLevel
    message: str
    timestamp: datetime
    current_value: float
    threshold_value: float
    suggested_actions: List[str] = field(default_factory=list)
    metadata: Dict[str, Any] = field(default_factory=dict)


@dataclass
class PerformanceTrend:
    """性能趋势"""
    metric_name: str
    trend_direction: str  # 'increasing', 'decreasing', 'stable'
    trend_strength: float  # 0-1
    prediction: Optional[float] = None
    confidence: float = 0.0
    time_window: timedelta = timedelta(hours=1)


@dataclass
class SystemResource:
    """系统资源使用情况"""
    cpu_percent: float
    memory_percent: float
    memory_used_mb: float
    memory_available_mb: float
    disk_usage_percent: float
    timestamp: datetime


class PerformanceMonitor:
    """增强性能监控器"""
    
    def __init__(self, component_name: str = "default", max_history_size: int = 1000):
        self.component_name = component_name
        self.max_history_size = max_history_size
        self.logger = logging.getLogger(__name__)
        
        # 性能指标历史（按类别分组）
        self.metrics_history = deque(maxlen=max_history_size)
        self.system_resources = deque(maxlen=max_history_size)
        self.operation_times = defaultdict(list)
        self.error_counts = defaultdict(int)
        self.success_counts = defaultdict(int)
        
        # 告警系统
        self.alerts = deque(maxlen=1000)
        self.alert_handlers: Dict[AlertLevel, List[Callable]] = {
            level: [] for level in AlertLevel
        }
        
        # 性能统计
        self.stats = {
            'total_operations': 0,
            'successful_operations': 0,
            'failed_operations': 0,
            'average_response_time': 0.0,
            'peak_memory_usage': 0.0,
            'peak_cpu_usage': 0.0,
            'algorithm_executions': 0,
            'error_rate': 0.0,
            'throughput': 0.0
        }
        
        # 增强的监控配置
        self.monitoring_enabled = True
        self.auto_collect_interval = 60  # 秒
        self.performance_thresholds = {
            'cpu_warning': 70.0,
            'cpu_critical': 85.0,
            'cpu_emergency': 95.0,
            'memory_warning': 75.0,
            'memory_critical': 90.0,
            'memory_emergency': 98.0,
            'response_time_warning': 3.0,
            'response_time_critical': 8.0,
            'response_time_emergency': 15.0,
            'error_rate_warning': 0.05,
            'error_rate_critical': 0.15,
            'error_rate_emergency': 0.30
        }
        
        # 启动自动收集线程
        self._start_auto_collection()
    
    def _start_auto_collection(self):
        """启动自动性能数据收集"""
        def collect_loop():
            while self.monitoring_enabled:
                try:
                    self._collect_system_resources()
                    time.sleep(self.auto_collect_interval)
                except Exception:
                    # 忽略收集错误，避免影响主程序
                    pass
        
        thread = threading.Thread(target=collect_loop, daemon=True)
        thread.start()
    
    def _collect_system_resources(self):
        """收集系统资源使用情况"""
        try:
            cpu_percent = psutil.cpu_percent(interval=1)
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('/')
            
            resource = SystemResource(
                cpu_percent=cpu_percent,
                memory_percent=memory.percent,
                memory_used_mb=memory.used / (1024 * 1024),
                memory_available_mb=memory.available / (1024 * 1024),
                disk_usage_percent=disk.percent,
                timestamp=datetime.now()
            )
            
            self.system_resources.append(resource)
            
            # 更新峰值统计
            self.stats['peak_cpu_usage'] = max(self.stats['peak_cpu_usage'], cpu_percent)
            self.stats['peak_memory_usage'] = max(self.stats['peak_memory_usage'], memory.percent)
            
        except Exception:
            # 忽略收集错误
            pass
    
    def record_operation_start(self, operation_name: str) -> str:
        """记录操作开始时间"""
        operation_id = f"{operation_name}_{int(time.time() * 1000)}"
        self.operation_times[operation_id] = [time.time()]
        return operation_id
    
    def record_operation_end(self, operation_id: str, success: bool = True, metadata: Dict[str, Any] = None):
        """记录操作结束时间"""
        if operation_id in self.operation_times:
            start_time = self.operation_times[operation_id][0]
            end_time = time.time()
            duration = end_time - start_time
            
            # 提取操作名称
            operation_name = operation_id.rsplit('_', 1)[0]
            
            # 记录性能指标
            metric = PerformanceMetric(
                name=f"{operation_name}_duration",
                value=duration,
                timestamp=datetime.now(),
                category="operation_time",
                unit="seconds",
                metadata=metadata or {}
            )
            self.metrics_history.append(metric)
            
            # 更新统计
            self.stats['total_operations'] += 1
            if success:
                self.stats['successful_operations'] += 1
                self.success_counts[operation_name] += 1
            else:
                self.stats['failed_operations'] += 1
                self.error_counts[operation_name] += 1
            
            # 更新平均响应时间
            total_time = sum(m.value for m in self.metrics_history if m.category == "operation_time")
            operation_count = len([m for m in self.metrics_history if m.category == "operation_time"])
            if operation_count > 0:
                self.stats['average_response_time'] = total_time / operation_count
            
            # 清理操作记录
            del self.operation_times[operation_id]
    
    def record_custom_metric(self, name: str, value: float, category: str = "custom", 
                           unit: str = "", metadata: Dict[str, Any] = None,
                           tags: Dict[str, str] = None,
                           threshold_config: Dict[str, float] = None):
        """记录增强自定义性能指标"""
        if metadata is None:
            metadata = {}
        if tags is None:
            tags = {}
        
        metric = PerformanceMetric(
            name=name,
            value=value,
            timestamp=datetime.now(),
            category=category,
            unit=unit,
            metadata=metadata,
            tags=tags,
            threshold_config=threshold_config
        )
        
        self.metrics_history.append(metric)
        
        # 智能阈值检查
        self._intelligent_threshold_check(metric)
        
        # 趋势分析
        self._analyze_trend(metric)
    
    def get_performance_summary(self) -> Dict[str, Any]:
        """获取性能摘要"""
        current_resource = self.system_resources[-1] if self.system_resources else None
        
        # 计算最近操作的平均时间
        recent_operations = [m for m in list(self.metrics_history)[-100:] 
                           if m.category == "operation_time"]
        recent_avg_time = (sum(m.value for m in recent_operations) / len(recent_operations)) \
                         if recent_operations else 0.0
        
        # 检查性能警告
        warnings = self._check_performance_warnings(current_resource, recent_avg_time)
        
        return {
            'timestamp': datetime.now().isoformat(),
            'system_resources': {
                'cpu_percent': current_resource.cpu_percent if current_resource else 0,
                'memory_percent': current_resource.memory_percent if current_resource else 0,
                'memory_used_mb': current_resource.memory_used_mb if current_resource else 0,
                'disk_usage_percent': current_resource.disk_usage_percent if current_resource else 0
            } if current_resource else {},
            'operation_stats': {
                'total_operations': self.stats['total_operations'],
                'success_rate': (self.stats['successful_operations'] / max(self.stats['total_operations'], 1)) * 100,
                'average_response_time': self.stats['average_response_time'],
                'recent_average_response_time': recent_avg_time
            },
            'peak_usage': {
                'peak_cpu_usage': self.stats['peak_cpu_usage'],
                'peak_memory_usage': self.stats['peak_memory_usage']
            },
            'warnings': warnings,
            'recommendations': self._generate_performance_recommendations(current_resource, recent_avg_time)
        }
    
    def _intelligent_threshold_check(self, metric: PerformanceMetric):
        """智能阈值检查"""
        # 使用自定义阈值配置或默认配置
        threshold_config = metric.threshold_config or self._get_default_thresholds(metric.name)
        
        if not threshold_config:
            return
        
        # 多级阈值检查
        for level_name, threshold_value in threshold_config.items():
            if metric.value > threshold_value:
                alert_level = self._parse_alert_level(level_name)
                if alert_level:
                    self._create_smart_alert(metric, alert_level, threshold_value)
                break
    
    def _get_default_thresholds(self, metric_name: str) -> Dict[str, float]:
        """获取默认阈值配置"""
        threshold_map = {
            'cpu_usage': {
                'warning': self.performance_thresholds['cpu_warning'],
                'critical': self.performance_thresholds['cpu_critical'],
                'emergency': self.performance_thresholds['cpu_emergency']
            },
            'memory_usage': {
                'warning': self.performance_thresholds['memory_warning'],
                'critical': self.performance_thresholds['memory_critical'],
                'emergency': self.performance_thresholds['memory_emergency']
            },
            'response_time': {
                'warning': self.performance_thresholds['response_time_warning'],
                'critical': self.performance_thresholds['response_time_critical'],
                'emergency': self.performance_thresholds['response_time_emergency']
            },
            'error_rate': {
                'warning': self.performance_thresholds['error_rate_warning'],
                'critical': self.performance_thresholds['error_rate_critical'],
                'emergency': self.performance_thresholds['error_rate_emergency']
            }
        }
        return threshold_map.get(metric_name, {})
    
    def _parse_alert_level(self, level_name: str) -> Optional[AlertLevel]:
        """解析告警级别"""
        try:
            return AlertLevel(level_name.lower())
        except ValueError:
            return None
    
    def _create_smart_alert(self, metric: PerformanceMetric, level: AlertLevel, threshold: float):
        """创建智能告警"""
        # 生成智能告警消息
        message = self._generate_alert_message(metric, level, threshold)
        
        # 生成建议操作
        suggested_actions = self._generate_suggested_actions(metric, level)
        
        alert = PerformanceAlert(
            metric_name=metric.name,
            level=level,
            message=message,
            timestamp=datetime.now(),
            current_value=metric.value,
            threshold_value=threshold,
            suggested_actions=suggested_actions,
            metadata={
                'component': self.component_name,
                'category': metric.category,
                'tags': metric.tags
            }
        )
        
        self.alerts.append(alert)
        self._handle_alert(alert)
    
    def _generate_alert_message(self, metric: PerformanceMetric, level: AlertLevel, threshold: float) -> str:
        """生成告警消息"""
        percentage_over = ((metric.value - threshold) / threshold) * 100
        
        messages = {
            AlertLevel.WARNING: f"{metric.name} 达到警告阈值: {metric.value:.2f}{metric.unit} (超出 {percentage_over:.1f}%)",
            AlertLevel.CRITICAL: f"{metric.name} 达到严重阈值: {metric.value:.2f}{metric.unit} (超出 {percentage_over:.1f}%)",
            AlertLevel.EMERGENCY: f"{metric.name} 达到紧急阈值: {metric.value:.2f}{metric.unit} (超出 {percentage_over:.1f}%)"
        }
        
        return messages.get(level, f"{metric.name} 异常: {metric.value:.2f}{metric.unit}")
    
    def _generate_suggested_actions(self, metric: PerformanceMetric, level: AlertLevel) -> List[str]:
        """生成建议操作"""
        actions = []
        
        if 'cpu' in metric.name.lower():
            if level == AlertLevel.WARNING:
                actions.extend(["检查CPU密集型进程", "考虑优化算法复杂度"])
            elif level in [AlertLevel.CRITICAL, AlertLevel.EMERGENCY]:
                actions.extend(["立即检查系统负载", "考虑增加计算资源", "暂停非关键任务"])
        
        elif 'memory' in metric.name.lower():
            if level == AlertLevel.WARNING:
                actions.extend(["检查内存泄漏", "清理缓存"])
            elif level in [AlertLevel.CRITICAL, AlertLevel.EMERGENCY]:
                actions.extend(["立即释放内存", "重启服务", "增加内存资源"])
        
        elif 'response_time' in metric.name.lower():
            actions.extend(["检查网络连接", "优化数据库查询", "启用缓存"])
        
        elif 'error_rate' in metric.name.lower():
            actions.extend(["检查错误日志", "验证输入数据", "检查系统依赖"])
        
        return actions
    
    def _handle_alert(self, alert: PerformanceAlert):
        """处理告警"""
        # 记录告警
        self.logger.warning(f"Performance Alert: {alert.message}")
        
        # 调用注册的告警处理器
        for handler in self.alert_handlers.get(alert.level, []):
            try:
                handler(alert)
            except Exception as e:
                self.logger.error(f"Alert handler error: {e}")
    
    def register_alert_handler(self, level: AlertLevel, handler: Callable[[PerformanceAlert], None]):
        """注册告警处理器"""
        self.alert_handlers[level].append(handler)
    
    def _analyze_trend(self, metric: PerformanceMetric):
        """分析指标趋势"""
        # 获取历史数据
        history = [m for m in list(self.metrics_history)[-50:] if m.name == metric.name]
        
        if len(history) >= 10:  # 需要足够的历史数据
            trend = self._calculate_trend(history)
            if trend and trend.trend_strength > 0.7:  # 强趋势
                self._handle_trend_alert(trend)
    
    def _calculate_trend(self, history: List[PerformanceMetric]) -> Optional[PerformanceTrend]:
        """计算趋势"""
        if len(history) < 5:
            return None
        
        values = [m.value for m in history]
        
        # 简单线性趋势计算
        n = len(values)
        x = list(range(n))
        
        # 计算斜率
        x_mean = sum(x) / n
        y_mean = sum(values) / n
        
        numerator = sum((x[i] - x_mean) * (values[i] - y_mean) for i in range(n))
        denominator = sum((x[i] - x_mean) ** 2 for i in range(n))
        
        if denominator == 0:
            return None
        
        slope = numerator / denominator
        
        # 确定趋势方向和强度
        if abs(slope) < 0.01:
            direction = 'stable'
            strength = 0.0
        elif slope > 0:
            direction = 'increasing'
            strength = min(abs(slope) * 10, 1.0)
        else:
            direction = 'decreasing'
            strength = min(abs(slope) * 10, 1.0)
        
        return PerformanceTrend(
            metric_name=history[0].name,
            trend_direction=direction,
            trend_strength=strength,
            time_window=timedelta(minutes=len(history))
        )
    
    def _handle_trend_alert(self, trend: PerformanceTrend):
        """处理趋势告警"""
        if trend.trend_direction == 'increasing' and trend.metric_name in ['cpu_usage', 'memory_usage', 'error_rate']:
            self.logger.warning(f"Trend Alert: {trend.metric_name} showing strong increasing trend (strength: {trend.trend_strength:.2f})")
    
    def get_performance_insights(self) -> Dict[str, Any]:
        """获取性能洞察"""
        insights = {
            'current_status': self._get_current_status(),
            'trends': self._get_trend_summary(),
            'predictions': self._get_performance_predictions(),
            'optimization_suggestions': self._get_optimization_suggestions(),
            'alerts_summary': self._get_alerts_summary()
        }
        return insights
    
    def _get_current_status(self) -> Dict[str, Any]:
        """获取当前状态"""
        return {
            'component': self.component_name,
            'monitoring_active': self.monitoring_enabled,
            'metrics_count': len(self.metrics_history),
            'alerts_count': len(self.alerts),
            'last_update': datetime.now().isoformat()
        }
    
    def _get_trend_summary(self) -> Dict[str, Any]:
        """获取趋势摘要"""
        trends = {}
        metric_names = set(m.name for m in self.metrics_history)
        
        for metric_name in metric_names:
            history = [m for m in self.metrics_history if m.name == metric_name]
            if len(history) >= 5:
                trend = self._calculate_trend(history)
                if trend:
                    trends[metric_name] = {
                        'direction': trend.trend_direction,
                        'strength': trend.trend_strength,
                        'confidence': trend.confidence
                    }
        return trends
    
    def _get_performance_predictions(self) -> Dict[str, Any]:
        """获取性能预测"""
        predictions = {}
        for metric_name in ['cpu_usage', 'memory_usage', 'response_time']:
            history = [m for m in self.metrics_history if metric_name in m.name]
            if len(history) >= 10:
                prediction = self._predict_metric_value(history)
                if prediction:
                    predictions[metric_name] = prediction
        return predictions
    
    def _predict_metric_value(self, history: List[PerformanceMetric]) -> Optional[Dict[str, Any]]:
        """预测指标值"""
        if len(history) < 10:
            return None
        
        values = [m.value for m in history[-10:]]
        
        # 简单的移动平均预测
        if len(values) >= 3:
            recent_trend = (values[-1] - values[-3]) / 2
        else:
            recent_trend = 0
        
        predicted_value = values[-1] + recent_trend
        
        # 计算置信度
        variance = sum((v - sum(values)/len(values))**2 for v in values) / len(values)
        confidence = max(0, 1 - (variance / (sum(values)/len(values) + 1)))
        
        return {
            'predicted_value': max(0, predicted_value),
            'confidence': confidence,
            'trend': recent_trend,
            'prediction_time': (datetime.now() + timedelta(minutes=30)).isoformat()
        }
    
    def _get_optimization_suggestions(self) -> List[Dict[str, Any]]:
        """获取优化建议"""
        suggestions = []
        
        # 基于当前资源使用情况的建议
        current_resource = self.system_resources[-1] if self.system_resources else None
        if current_resource:
            if current_resource.cpu_percent > 70:
                suggestions.append({
                    'type': 'performance',
                    'priority': 8,
                    'title': 'CPU使用率优化',
                    'description': f'CPU使用率达到{current_resource.cpu_percent:.1f}%，建议优化',
                    'actions': ['考虑使用更高效的算法', '启用多线程处理', '优化循环和递归逻辑']
                })
            
            if current_resource.memory_percent > 75:
                suggestions.append({
                    'type': 'performance',
                    'priority': 7,
                    'title': '内存使用优化',
                    'description': f'内存使用率达到{current_resource.memory_percent:.1f}%，建议优化',
                    'actions': ['检查内存泄漏', '优化数据结构', '启用垃圾回收']
                })
        
        # 基于错误率的建议
        total_ops = self.stats['total_operations']
        if total_ops > 0:
            error_rate = self.stats['failed_operations'] / total_ops
            if error_rate > 0.1:
                suggestions.append({
                    'type': 'reliability',
                    'priority': 9,
                    'title': '错误率过高',
                    'description': f'当前错误率为{error_rate:.2%}，需要立即处理',
                    'actions': ['检查错误日志', '验证输入数据', '增强错误处理']
                })
        
        # 基于响应时间的建议
        avg_response_time = self.stats['average_response_time']
        if avg_response_time > 5:
            suggestions.append({
                'type': 'performance',
                'priority': 6,
                'title': '响应时间优化',
                'description': f'平均响应时间为{avg_response_time:.2f}秒，建议优化',
                'actions': ['启用缓存机制', '优化数据库查询', '使用CDN加速']
            })
        
        return sorted(suggestions, key=lambda x: x['priority'], reverse=True)
    
    def _get_alerts_summary(self) -> Dict[str, Any]:
        """获取告警摘要"""
        recent_alerts = [a for a in self.alerts if (datetime.now() - a.timestamp).total_seconds() < 3600]
        
        alert_counts = {level.value: 0 for level in AlertLevel}
        for alert in recent_alerts:
            alert_counts[alert.level.value] += 1
        
        return {
            'total_alerts': len(recent_alerts),
            'alert_counts': alert_counts,
            'latest_alert': recent_alerts[-1].message if recent_alerts else None
        }
    
    def _check_performance_warnings(self, current_resource: Optional[SystemResource], 
                                  recent_avg_time: float) -> List[Dict[str, str]]:
        """检查性能警告（保持向后兼容）"""
        warnings = []
        
        if current_resource:
            # CPU警告
            if current_resource.cpu_percent >= self.performance_thresholds['cpu_critical']:
                warnings.append({
                    'type': 'critical',
                    'category': 'cpu',
                    'message': f'CPU使用率过高: {current_resource.cpu_percent:.1f}%'
                })
            elif current_resource.cpu_percent >= self.performance_thresholds['cpu_warning']:
                warnings.append({
                    'type': 'warning',
                    'category': 'cpu',
                    'message': f'CPU使用率较高: {current_resource.cpu_percent:.1f}%'
                })
            
            # 内存警告
            if current_resource.memory_percent >= self.performance_thresholds['memory_critical']:
                warnings.append({
                    'type': 'critical',
                    'category': 'memory',
                    'message': f'内存使用率过高: {current_resource.memory_percent:.1f}%'
                })
            elif current_resource.memory_percent >= self.performance_thresholds['memory_warning']:
                warnings.append({
                    'type': 'warning',
                    'category': 'memory',
                    'message': f'内存使用率较高: {current_resource.memory_percent:.1f}%'
                })
        
        # 响应时间警告
        if recent_avg_time >= self.performance_thresholds['response_time_critical']:
            warnings.append({
                'type': 'critical',
                'category': 'response_time',
                'message': f'平均响应时间过长: {recent_avg_time:.2f}秒'
            })
        elif recent_avg_time >= self.performance_thresholds['response_time_warning']:
            warnings.append({
                'type': 'warning',
                'category': 'response_time',
                'message': f'平均响应时间较长: {recent_avg_time:.2f}秒'
            })
        
        return warnings
    
    def _generate_performance_recommendations(self, current_resource: Optional[SystemResource],
                                            recent_avg_time: float) -> List[str]:
        """生成性能优化建议"""
        recommendations = []
        
        if current_resource:
            # CPU优化建议
            if current_resource.cpu_percent > 80:
                recommendations.extend([
                    "考虑减少并发操作数量",
                    "优化算法复杂度",
                    "使用更高效的数据结构"
                ])
            
            # 内存优化建议
            if current_resource.memory_percent > 80:
                recommendations.extend([
                    "清理不必要的缓存数据",
                    "减少同时处理的问题数量",
                    "考虑增加系统内存"
                ])
        
        # 响应时间优化建议
        if recent_avg_time > 5.0:
            recommendations.extend([
                "优化数据库查询",
                "使用缓存机制",
                "考虑异步处理"
            ])
        
        # 错误率优化建议
        total_ops = self.stats['total_operations']
        if total_ops > 0:
            error_rate = (self.stats['failed_operations'] / total_ops) * 100
            if error_rate > 10:
                recommendations.extend([
                    "检查输入验证逻辑",
                    "改进错误处理机制",
                    "增加系统健康检查"
                ])
        
        return recommendations
    
    def get_operation_statistics(self) -> Dict[str, Any]:
        """获取操作统计信息"""
        # 按操作类型统计
        operation_stats = {}
        for operation_name in set(list(self.success_counts.keys()) + list(self.error_counts.keys())):
            success_count = self.success_counts[operation_name]
            error_count = self.error_counts[operation_name]
            total_count = success_count + error_count
            
            # 计算该操作的平均时间
            operation_times = [m.value for m in self.metrics_history 
                             if m.name == f"{operation_name}_duration"]
            avg_time = sum(operation_times) / len(operation_times) if operation_times else 0.0
            
            operation_stats[operation_name] = {
                'total_count': total_count,
                'success_count': success_count,
                'error_count': error_count,
                'success_rate': (success_count / max(total_count, 1)) * 100,
                'average_time': avg_time
            }
        
        return operation_stats
    
    def get_resource_history(self, hours: int = 24) -> List[Dict[str, Any]]:
        """获取资源使用历史"""
        cutoff_time = datetime.now() - timedelta(hours=hours)
        
        history = []
        for resource in self.system_resources:
            if resource.timestamp >= cutoff_time:
                history.append({
                    'timestamp': resource.timestamp.isoformat(),
                    'cpu_percent': resource.cpu_percent,
                    'memory_percent': resource.memory_percent,
                    'memory_used_mb': resource.memory_used_mb,
                    'disk_usage_percent': resource.disk_usage_percent
                })
        
        return history
    
    def export_performance_report(self, filepath: str):
        """导出性能报告"""
        report = {
            'generated_at': datetime.now().isoformat(),
            'summary': self.get_performance_summary(),
            'operation_statistics': self.get_operation_statistics(),
            'resource_history': self.get_resource_history(),
            'configuration': {
                'max_history_size': self.max_history_size,
                'auto_collect_interval': self.auto_collect_interval,
                'performance_thresholds': self.performance_thresholds
            }
        }
        
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(report, f, indent=2, ensure_ascii=False)
    
    def reset_statistics(self):
        """重置统计信息"""
        self.metrics_history.clear()
        self.system_resources.clear()
        self.operation_times.clear()
        self.error_counts.clear()
        self.success_counts.clear()
        
        self.stats = {
            'total_operations': 0,
            'successful_operations': 0,
            'failed_operations': 0,
            'average_response_time': 0.0,
            'peak_memory_usage': 0.0,
            'peak_cpu_usage': 0.0
        }
    
    def stop_monitoring(self):
        """停止性能监控"""
        self.monitoring_enabled = False


class TrendAnalyzer:
    """趋势分析器"""
    
    def __init__(self):
        self.min_data_points = 5
        self.trend_threshold = 0.1
    
    def analyze(self, metrics: List[PerformanceMetric]) -> Optional[PerformanceTrend]:
        """分析指标趋势"""
        if len(metrics) < self.min_data_points:
            return None
        
        values = [m.value for m in metrics]
        timestamps = [m.timestamp for m in metrics]
        
        # 计算线性回归
        trend_info = self._calculate_linear_trend(values)
        
        if not trend_info:
            return None
        
        # 预测未来值
        prediction = self._predict_next_value(values, trend_info['slope'])
        
        return PerformanceTrend(
            metric_name=metrics[0].name,
            trend_direction=trend_info['direction'],
            trend_strength=trend_info['strength'],
            prediction=prediction,
            confidence=trend_info['confidence'],
            time_window=timestamps[-1] - timestamps[0]
        )
    
    def _calculate_linear_trend(self, values: List[float]) -> Optional[Dict[str, Any]]:
        """计算线性趋势"""
        n = len(values)
        if n < 2:
            return None
        
        x = list(range(n))
        x_mean = sum(x) / n
        y_mean = sum(values) / n
        
        # 计算斜率和相关系数
        numerator = sum((x[i] - x_mean) * (values[i] - y_mean) for i in range(n))
        denominator_x = sum((x[i] - x_mean) ** 2 for i in range(n))
        denominator_y = sum((values[i] - y_mean) ** 2 for i in range(n))
        
        if denominator_x == 0 or denominator_y == 0:
            return None
        
        slope = numerator / denominator_x
        correlation = numerator / (denominator_x * denominator_y) ** 0.5
        
        # 确定趋势方向和强度
        if abs(slope) < self.trend_threshold:
            direction = 'stable'
            strength = 0.0
        elif slope > 0:
            direction = 'increasing'
            strength = min(abs(correlation), 1.0)
        else:
            direction = 'decreasing'
            strength = min(abs(correlation), 1.0)
        
        return {
            'direction': direction,
            'strength': strength,
            'slope': slope,
            'confidence': abs(correlation)
        }
    
    def _predict_next_value(self, values: List[float], slope: float) -> float:
        """预测下一个值"""
        if not values:
            return 0.0
        
        last_value = values[-1]
        return max(0, last_value + slope)


class PerformancePredictor:
    """性能预测器"""
    
    def __init__(self):
        self.prediction_window = timedelta(minutes=30)
        self.min_history_size = 10
    
    def predict(self, metric_name: str, metrics_history: List[PerformanceMetric]) -> Optional[Dict[str, Any]]:
        """预测性能指标"""
        # 收集相关历史数据
        relevant_metrics = [m for m in metrics_history if m.name == metric_name]
        
        if len(relevant_metrics) < self.min_history_size:
            return None
        
        # 按时间排序
        relevant_metrics.sort(key=lambda x: x.timestamp)
        recent_metrics = relevant_metrics[-20:]  # 使用最近20个数据点
        
        # 简单的移动平均预测
        values = [m.value for m in recent_metrics]
        
        # 计算趋势
        if len(values) >= 3:
            recent_trend = (values[-1] - values[-3]) / 2
        else:
            recent_trend = 0
        
        # 预测值
        predicted_value = values[-1] + recent_trend
        
        # 计算置信度（基于历史数据的稳定性）
        variance = sum((v - sum(values)/len(values))**2 for v in values) / len(values)
        confidence = max(0, 1 - (variance / (sum(values)/len(values) + 1)))
        
        return {
            'predicted_value': max(0, predicted_value),
            'confidence': confidence,
            'trend': recent_trend,
            'prediction_time': datetime.now() + self.prediction_window
        }


class OptimizationAdvisor:
    """优化建议器"""
    
    def __init__(self):
        self.suggestion_rules = self._load_suggestion_rules()
    
    def generate_suggestions(self, current_metrics: Dict[str, PerformanceMetric], 
                           performance_stats: Dict[str, Any],
                           alerts: List[PerformanceAlert]) -> List[Dict[str, Any]]:
        """生成优化建议"""
        suggestions = []
        
        # 基于当前指标的建议
        suggestions.extend(self._analyze_current_metrics(current_metrics))
        
        # 基于性能统计的建议
        suggestions.extend(self._analyze_performance_stats(performance_stats))
        
        # 基于告警的建议
        suggestions.extend(self._analyze_alerts(alerts))
        
        # 去重和排序
        unique_suggestions = self._deduplicate_suggestions(suggestions)
        return sorted(unique_suggestions, key=lambda x: x['priority'], reverse=True)
    
    def _load_suggestion_rules(self) -> Dict[str, Any]:
        """加载建议规则"""
        return {
            'cpu_optimization': {
                'high_cpu': [
                    "考虑使用更高效的算法",
                    "启用多线程处理",
                    "优化循环和递归逻辑"
                ],
                'cpu_spikes': [
                    "检查是否有CPU密集型操作",
                    "考虑异步处理"
                ]
            },
            'memory_optimization': {
                'high_memory': [
                    "检查内存泄漏",
                    "优化数据结构",
                    "启用垃圾回收"
                ],
                'memory_growth': [
                    "监控对象生命周期",
                    "减少缓存大小"
                ]
            },
            'response_time_optimization': [
                "启用缓存机制",
                "优化数据库查询",
                "使用CDN加速"
            ]
        }
    
    def _analyze_current_metrics(self, metrics: Dict[str, PerformanceMetric]) -> List[Dict[str, Any]]:
        """分析当前指标"""
        suggestions = []
        
        for metric in metrics.values():
            if 'cpu' in metric.name.lower() and metric.value > 70:
                suggestions.append({
                    'type': 'performance',
                    'priority': 8,
                    'title': 'CPU使用率优化',
                    'description': f'CPU使用率达到{metric.value:.1f}%，建议优化',
                    'actions': self.suggestion_rules['cpu_optimization']['high_cpu']
                })
            
            elif 'memory' in metric.name.lower() and metric.value > 75:
                suggestions.append({
                    'type': 'performance',
                    'priority': 7,
                    'title': '内存使用优化',
                    'description': f'内存使用率达到{metric.value:.1f}%，建议优化',
                    'actions': self.suggestion_rules['memory_optimization']['high_memory']
                })
        
        return suggestions
    
    def _analyze_performance_stats(self, stats: Dict[str, Any]) -> List[Dict[str, Any]]:
        """分析性能统计"""
        suggestions = []
        
        error_rate = stats.get('error_rate', 0)
        if error_rate > 0.1:
            suggestions.append({
                'type': 'reliability',
                'priority': 9,
                'title': '错误率过高',
                'description': f'当前错误率为{error_rate:.2%}，需要立即处理',
                'actions': ['检查错误日志', '验证输入数据', '增强错误处理']
            })
        
        avg_response_time = stats.get('average_response_time', 0)
        if avg_response_time > 5:
            suggestions.append({
                'type': 'performance',
                'priority': 6,
                'title': '响应时间优化',
                'description': f'平均响应时间为{avg_response_time:.2f}秒，建议优化',
                'actions': self.suggestion_rules['response_time_optimization']
            })
        
        return suggestions
    
    def _analyze_alerts(self, alerts: List[PerformanceAlert]) -> List[Dict[str, Any]]:
        """分析告警"""
        suggestions = []
        
        recent_alerts = [a for a in alerts if (datetime.now() - a.timestamp).total_seconds() < 1800]
        
        if len(recent_alerts) > 5:
            suggestions.append({
                'type': 'monitoring',
                'priority': 8,
                'title': '告警频率过高',
                'description': f'最近30分钟内产生了{len(recent_alerts)}个告警',
                'actions': ['检查系统稳定性', '调整告警阈值', '增强监控策略']
            })
        
        return suggestions
    
    def _deduplicate_suggestions(self, suggestions: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """去重建议"""
        seen_titles = set()
        unique_suggestions = []
        
        for suggestion in suggestions:
            if suggestion['title'] not in seen_titles:
                seen_titles.add(suggestion['title'])
                unique_suggestions.append(suggestion)
        
        return unique_suggestions


# 全局性能监控器实例
performance_monitor = PerformanceMonitor()


def monitor_performance(operation_name: str):
    """装饰器：自动监控函数性能"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            operation_id = performance_monitor.record_operation_start(operation_name)
            success = True
            result = None
            
            try:
                result = func(*args, **kwargs)
                return result
            except Exception as e:
                success = False
                raise
            finally:
                # 提取结果元数据
                metadata = {}
                if hasattr(result, '__dict__'):
                    metadata['result_type'] = type(result).__name__
                elif isinstance(result, dict) and 'status' in result:
                    metadata['status'] = result['status']
                
                performance_monitor.record_operation_end(operation_id, success, metadata)
        
        return wrapper
    return decorator